package io.hepu.robotize.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Tomcat Servlet WebServer
 */
@Configuration
public class ServletConfiguration {
    @Value("${server.port.http:80}")
    private int httpPort;

    @Value("${server.port.redirect:443}")
    private int redirectPort;

    @Bean
    public TomcatServletWebServerFactory servletCustomizer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            // Due to CONFIDENTIAL and /*, this will cause Tomcat to redirect every request to HTTPS.
            // You can configure multiple patterns and multiple constraints if you need more control over what is and is not redirected.
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(createHttpConnector()); // 添加http支持
        return tomcat;
    }

    private Connector createHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        // Set the scheme that will be assigned to requests received through this connector
        // @param scheme The new scheme
        connector.setScheme("http");

        // Set the port number on which we listen for requests.
        // @param port The new port number
        connector.setPort(httpPort);

        // Set the secure connection flag that will be assigned to requests received through this connector.
        // @param secure The new secure connection flag
        // if connector.setSecure(true), the http use the http and https use the https;
        // else if connector.setSecure(false), the http redirect to https;
        connector.setSecure(true);

        // @param redirectPort The redirect port number (non-SSL to SSL)
        connector.setRedirectPort(redirectPort);
        return connector;
    }
}
